package Sourcecode

import (
	dbc "../dataBase"
	"../model"
	"database/sql"
	"gopkg.in/mgo.v2/bson"
	common"../Common"
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	_ "reflect"
	"strconv"
	_ "testing"
	"time"
	base"../dataBase"
)


func GetQuestion()error {
	var db,err=base.GetMysqlDb()
	if(err!=nil){
		return common.New("链接Mysql数据库失败")
	}
	fmt.Println("创建Mysql连接")
	var t=time.Now().UnixNano()/1e6

	//查询数据库
	query, err := db.Query("select * from Questions")
	if err != nil {
		fmt.Println("查询数据库失败", err.Error())
		return common.New("获取数据失败")
	}
	defer query.Close()
	fmt.Println("Questions查询成功开始格式化数据")
	var cha=make(chan map[string][]Model.Answer)
	fmt.Println("开始异步获取问题答案")
	go getansers(db,cha)//开始异步获取问题答案数据forMysql
	//读出查询出的列字段名
	cols, _ := query.Columns()
	//values是每个列的值，这里获取到byte里
	values := make([][]byte, len(cols))
	//query.Scan的参数，因为每次查询出来的列是不定长的，用len(cols)定住当次查询的长度
	scans := make([]interface{}, len(cols))
	//让每一行数据都填充到[][]byte里面
	for i := range values {
		scans[i] = &values[i]
	}
	//最后得到的map
	results := make(map[int]Model.Questions)
	i := 0
	fmt.Println("等待问题处理")
	var answers=<-cha
	close(cha)//关闭信道
	db.Close()//关闭Sql连接
	if(answers==nil){
		fmt.Println("查询数据失败,未获取到答案数据", err.Error())
	}
	var t3=time.Now().UnixNano()/1e6
	fmt.Println("开始序列化答案")
	for query.Next() { //循环，让游标往下推
		if err := query.Scan(scans...); err != nil { //query.Scan查询出来的不定长值放到scans[i] = &values[i],也就是每行都放在values里
			fmt.Println(err)
			return err
		}

		row := make(map[string]interface{}) //每行数据

		for k, v := range values { //每行数据是放在values里面，现在把它挪到row里
			key := cols[k]
			row[key] = string(v)
		}
		mtype,_ :=strconv.ParseInt(row["Type"].(string),10,32)
		difficulty,_ :=strconv.ParseInt(row["Difficulty"].(string),10,32)
		faceType,_ :=strconv.ParseInt(row["FaceType"].(string),10,32)
		state,_ :=strconv.ParseInt(row["State"].(string),10,32)
		results[i] = Model.Questions{
			QuestionsID :row["Questionsid"].(string),
			SyllabusKnowledgePointID:row["SyllabusKnowledgePointID"].(string),
			Title:row["Title"].(string),
			Name:row["Name"].(string),
			AddUserid:row["AddUserid"].(string),
			AddTime:row["AddTime"].(string),
			Type:int32(mtype),
			Difficulty:int32(difficulty),
			FaceType:int32(faceType),
			State:int32(state),
			Answers:answers[row["Questionsid"].(string)],
		}
		//装入结果集中
		i++
	}

	//查询出来的数组
	fmt.Println("格式化完成开始导入数据")
	fmt.Println(time.Now().Format("2006-01-02 15:04:05"))
	a,b:=0,0
	for _, v := range results {
		selector := bson.M{"questionsID": v.QuestionsID}
		data := bson.M{"$set": v}
		 dbc.Upsert("db","Questions",selector,data)
		//fmt.Printf("%+v\n------------------------------\n",v)

		}
	fmt.Printf("成功:%d,失败:%d",a,b)
	var t2 =time.Now().UnixNano()/1e6
	fmt.Printf("共用时:%d,,序列化用时%d\n",t2-t,t3-t)
	db.Close()
	return nil
	//var arr []Model.Questions
	//dbc.FindAll("db","Questions",bson.M{},nil,&arr)
	////fmt.Print(arr)
	//fmt.Printf("共有数据:%d",len(arr))
}

func getansers(db *sql.DB,cha chan map[string][]Model.Answer ) {
	//查询数据库
	query, err := db.Query("select * from answers")
	if err != nil {
		fmt.Printf("查询数据库失败", err.Error())
		cha <- nil
		return
	}
	defer query.Close()

	//读出查询出的列字段名
	cols, _ := query.Columns()
	//values是每个列的值，这里获取到byte里
	values := make([][]byte, len(cols))
	//query.Scan的参数，因为每次查询出来的列是不定长的，用len(cols)定住当次查询的长度
	scans := make([]interface{}, len(cols))
	//让每一行数据都填充到[][]byte里面
	for i := range values {
		scans[i] = &values[i]
	}
	//最后得到的map
	results := make(map[string][]Model.Answer)
	fmt.Println("Ansers查询成功开始序列化")
	for query.Next() { //循环，让游标往下推
		if err := query.Scan(scans...); err != nil { //query.Scan查询出来的不定长值放到scans[i] = &values[i],也就是每行都放在values里
			fmt.Println(err)
			cha <- nil
			return
		}

		row := make(map[string]interface{}) //每行数据
		i := 0
		for k, v := range values { //每行数据是放在values里面，现在把它挪到row里
			key := cols[k]
			row[key] = string(v)
		}
		realAnswer,_ :=strconv.ParseInt(row["RealAnswer"].(string),10,32)
		isdecompression,_ :=strconv.ParseInt(row["Isdecompression"].(string),10,32)
		var dat= Model.Answer{
			Questionsid :row["Questionsid"].(string),
			Answerid:row["Answerid"].(string),
			Content:row["Content"].(string),
			AddUserid:row["AddUserid"].(string),
			AddTime:row["AddTime"].(string),
			RealAnswer:int32(realAnswer),
			Isdecompression:int32(isdecompression),
		}


		results[dat.Questionsid]=append(results[dat.Questionsid],dat )
		//fmt.Printf("断点---------------------------")
		//fmt.Printf("%+v\n",results[dat.Questionsid])
		//装入结果集中
		i++
	}
	fmt.Println("问题处理完成")
	//查询出来的数组
	cha <- results
	return
	//for s, v := range results {
	//	//go dbc.Insert("db","Questions",v,cha)
	//	fmt.Printf("%s\n",s)
	//	selector := bson.M{"questionsID": s}
	//	data := bson.M{"$set": bson.M{"answers": v}}
	//	err= dbc.Update("db","Questions",selector,data)
	//	if(err!=nil){
	//		fmt.Printf("测试:%+s\n------------------\n",err)
	//	}
	//}
	//
	//var arr []Model.Questions
	//dbc.FindAll("db","Questions",bson.M{},nil,&arr)
	////fmt.Print(arr)
	//fmt.Printf("共有数据%+v",arr[5])
}
